<!--
 * @author liganghao
 用户人员管理
 -->
<template>
  <div id="department-manage">
    <div class="btn-container">
      <div class="btn-container-title">
        <span>部门管理</span>
        <span v-if="orgbread">,当前选择：</span>
        <span v-if="orgbread" class="btn-container-title-select">{{ orgbread }}</span>
      </div>
      <div class="btn-container-btns">
        <el-button class="filter-item" style="margin-left: 10px" @click="handleDownload">模版下载</el-button>
        <el-button class="filter-item" @click="handleUpload">批量上传</el-button>
        <el-button
          v-if="isShowBtn"
          class="filter-item"
          style="padding: 10px 30px; margin-left: 10px; margin-bottom: 0"
          @click="handleCreate"
        >新增下级
        </el-button>
        <el-button
          v-if="isShowBtn"
          class="filter-item"
          style="padding: 10px 30px; margin-left: 10px; margin-bottom: 0"
          @click="handleDelete"
        >删除
        </el-button>
      </div>
    </div>
    <el-container class="org-row-container">
      <split-pane split="vertical" :min-percent="0" :default-percent="28">
        <template slot="paneL">
          <div class="treeBox">
            <div class="search-tree-wrap">
              <el-input
                v-model.trim="orgName"
                style="width:75%"
                placeholder="部门名称搜索"
                class="search-input"
                clearable
                @clear="clearSearchOrgTree"
              />
              <el-button class="filter-item tree-filter" type="primary" @click="handleFilterOrgTree">搜索
              </el-button>
            </div>
            <el-tree
              v-if="!issearchorg"
              ref="bmtree"
              key="lodorg"
              v-loading="orgtreeLoading"
              :data="orgtreeData"
              :props="defaultPropsOrg"
              :expand-on-click-node="false"
              highlight-current
              node-key="id"
              :load="loadtreeOrg"
              lazy
              @node-click="handleClickOrg"
            />
            <el-tree
              v-if="issearchorg"
              ref="bmtree"
              key="neworg"
              v-loading="orgtreeLoading"
              :data="orgtreeData"
              :props="defaultPropsOrg"
              default-expand-all
              :expand-on-click-node="false"
              highlight-current
              @node-click="handleClickOrg"
            />
          </div>
        </template>

        <template slot="paneR">
          <el-main class="user-main enterpriseinfo">
            <div v-if="!isShow" class="ts-con">
              <div class="ts">
                <i class="el-icon-info" />
                <span v-html="showMsg" />
              </div>
            </div>
            <div v-else id="orginfo-container">
              <el-form
                ref="dataForm"
                v-loading="submitloading"
                :model="temp"
                :rules="rules"
                class="dataForm"
                label-position="right"
                label-width="80px"
                style="width: 350px; overflow: auto"
              >
                <el-form-item label="部门名称" prop="name">
                  <el-input v-model.trim="temp.name" placeholder="请输入部门名称" />
                </el-form-item>
                <el-form-item label="部门编号" prop="code">
                  <el-input v-model.trim="temp.code" placeholder="请输入部门编号" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                  <el-input v-model.trim="temp.sort" placeholder="请输入序号" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="temp.status">
                    <el-radio v-for="v in dict.ZT" :key="v.dictValue" :label="v.dictValue">
                      {{ v.dictName }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button style="padding: 8px 30px" @click="isShow = false">取消</el-button>
                  <el-button
                    style="padding: 8px 30px"
                    type="primary"
                    @click="insetOrUpdate"
                  >确定
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-main>
        </template>
      </split-pane>
    </el-container>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :title="'批量上传'"
      :visible.sync="uploadVisible"
      center
      width="450px"
    >
      <el-upload
        ref="upload"
        v-loading="loadingUpload"
        element-loading-text="正在上传请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :action="uploadaction"
        :headers="uploadHeaders"
        :data="uploadData"
        accept=".xls, .xlsx"
        class="upload-model"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip" />
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px" @click="uploadVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px" type="primary" @click="uploadSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  specialText
} from '@/utils/validate'
import {
  insert,
  update,
  del,
  get,
  getComTreeSync,
  getOrgTreeSync,
  getDictByCode,
  roleListByName,
  searchOrgTreeSync
} from '@/views/department/api/index'
import permission from '@/directive/permission/index.js' // 权限判断指令
import {
  mapGetters
} from 'vuex'
import {
  getToken
} from '@/utils/auth'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import splitPane from 'vue-splitpane'
import { importSign, exportSign } from '@/utils/fileImportOrExportSign'

export default {
  name: 'DepartmentAuthority',
  directives: {
    permission,
    elDragDialog
  },
  components: {
    splitPane
  },
  data() {
    return {
      orgtreeLoading: false,
      comtreeLoading: false,
      submitloading: false,
      isShow: false,
      showMsg: '单击左侧菜单项进行维护',
      issearchtree: false,
      comtreeData: [],
      issearchorg: false,
      orgtreeData: [],
      defaultProps: {
        children: 'list',
        label: 'orgName'
      },
      defaultPropsOrg: {
        children: 'list',
        label: 'name'
      },
      combread: '',
      orgbread: '',
      comName: '',
      orgName: '',
      formStatus: '',
      curComData: {},
      curOrgData: {},
      temp: {
        orgId: '',
        parentId: '',
        code: '',
        name: '',
        status: 'ZT01', // 默认开启
        sort: 0,
        id: ''
      },
      rules: {
        name: [{
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        }, {
          validator: specialText,
          trigger: 'blur'
        }],
        state: [{
          required: true,
          message: '请选择状态',
          trigger: 'change'
        }],
        code: [{
          required: true,
          message: '请输入部门编号',
          trigger: 'blur'
        }],
        sort: [{
          validator: (rule, value, callback) => {
            if (value !== '') {
              if ((/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value) === false) {
                callback(new Error('请填写大于0的数字'))
              } else {
                callback()
              }
            } else {
              callback()
            }
          },
          trigger: 'change'
        }]
      },
      isShowAddBtn: false,
      isShowBtn: false,
      dict: {
        ZT: [] // 状态
      },
      uploadVisible: false,
      loadingUpload: false,
      uploadaction: '/API-ENTERPRISE-BACKEND/backend/departmentInfo/adminImportDept',
      uploadHeaders: {
        'ttsxyhcs': getToken()
      },
      uploadData: {
        orgId: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  created() {
    this.getComTreeData()
    for (const key in this.dict) {
      this.getDict(key)
    }
  },
  methods: {
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = response.data.data[0].list
        }).catch(error => {
          reject(error)
        })
      })
    },
    refreshNodeBy(id) {
      const node = this.$refs.bmtree.getNode(id) // 通过节点id找到对应树节点对象
      node.loaded = false
      node.expand() // 主动调用展开节点方法，重新查询该节点下的所有子节点
    },
    /**
     * 清空搜索组织
     */
    clearSearchComTree() {
      this.comName = ''
      this.issearchtree = false
      this.getComTreeData()
    },
    /**
     * 按组织名称查询
     */
    handleFilterComTree() {
      if (this.comName === '') {
        this.issearchtree = false
        this.getComTreeData()
      } else {
        this.comtreeLoading = true
        return new Promise((resolve, reject) => {
          roleListByName({
            orgName: this.comName
          }).then(response => {
            this.comtreeLoading = false
            this.comtreeData = response.data.data
            this.issearchtree = true
          }).catch(error => {
            reject(error)
            this.issearchtree = false
            this.comtreeLoading = false
          })
        })
      }
    },
    /**
     * 获取组织数据
     */
    getComTreeData() {
      this.curOrgData.id = this.user.orgId
      this.handleClickCom({
        id: this.user.orgId
      })
      /* this.comtreeLoading = true
      return new Promise((resolve, reject) => {
        getComTreeSync().then(response => {
          this.comtreeLoading = false
          const data = response.data.data || []
          this.comtreeData = data
          if (data && data.length > 0) {
            this.curOrgData.id = data[0].id
            this.handleClickCom(data[0])
          }
        }).catch(error => {
          reject(error)
          this.comtreeLoading = false
        })
      })*/
    },
    /**
     * 异步加载组织数据
     */
    loadtreeCom(node, resolve) {
      this.comtreeLoading = true
      if (node.level !== 0) {
        getComTreeSync(node.data.id).then(res => {
          this.comtreeLoading = false
          resolve(res.data.data)
        }).catch(res => {
          this.comtreeLoading = false
          resolve([])
        })
      }
    },
    /**
     * 清空搜索部门
     */
    clearSearchOrgTree() {
      this.orgName = ''
      this.orgbread = ''
      this.curOrgData = {}
      this.isShow = false
      this.isShowAddBtn = true
      this.isShowBtn = false
      this.issearchorg = false
      this.getOrgTreeData()
    },
    /**
     * 按部门名称查询
     */
    handleFilterOrgTree() {
      if (this.orgName === '') {
        this.clearSearchOrgTree()
      } else {
        this.orgbread = ''
        this.curOrgData = {}
        this.isShow = false
        this.isShowAddBtn = true
        this.isShowBtn = false
        this.issearchorg = false
        this.orgtreeLoading = true
        return new Promise((resolve, reject) => {
          searchOrgTreeSync({
            orgId: this.curComData.id,
            parentId: this.curOrgData.id || -1,
            name: this.orgName
          }).then(response => {
            this.orgtreeLoading = false
            this.orgtreeData = response.data.data
            this.issearchorg = true
          }).catch(error => {
            reject(error)
            this.issearchorg = false
            this.orgtreeLoading = false
          })
        })
      }
    },
    /**
     * 获取部门数据
     */
    getOrgTreeData() {
      this.orgtreeLoading = true
      return new Promise((resolve, reject) => {
        getOrgTreeSync({
          orgId: this.curComData.id,
          parentId: this.curOrgData.id || -1
        }).then(response => {
          this.orgtreeLoading = false
          this.orgtreeData = response.data.data
        }).catch(error => {
          reject(error)
          this.orgtreeLoading = false
        })
      })
    },

    /**
     * 异步加载部门数据
     */
    loadtreeOrg(node, resolve) {
      if (node.level !== 0) {
        this.orgtreeLoading = true
        getOrgTreeSync({
          parentId: node.data.id
        }).then(res => {
          this.orgtreeLoading = false
          resolve(res.data.data)
        }).catch(res => {
          this.orgtreeLoading = false
          resolve([])
        })
      }
    },
    /**
     * 点击选中组织获取当前组织下的部门
     */
    handleClickCom(data) {
      console.log(data, '----')
      this.curComData = Object.assign({}, data)
      // this.combread = data.orgNameAll.replace('/', '>')
      this.orgbread = ''
      this.curOrgData = {}
      this.isShow = false
      this.isShowAddBtn = true
      this.isShowBtn = false
      this.getOrgTreeData(data.id)
    },
    /**
     * 点击部门树
     */
    handleClickOrg(data) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.1)'
      })
      return new Promise((resolve, reject) => {
        get(data.id).then((res) => {
          loading.close()
          this.isShowBtn = true
          this.curOrgData = Object.assign({}, res.data.data)
          try {
            this.orgbread = data.nameAll.replace('/', '>')
          } catch (error) {
            console.log(error)
          }
          this.handleUpdate()
        }).catch(error => {
          reject(error)
          loading.close()
        })
      })
    },
    resetTemp() {
      this.temp = {
        orgId: this.curComData.id,
        parentId: this.curOrgData.id,
        code: '',
        name: '',
        status: 'ZT01', // 默认开启
        sort: 0,
        id: ''
      }
    },
    handleUpload() {
      this.uploadData.orgId = this.user.orgId
      this.uploadVisible = true
      this.$nextTick(() => {
        this.$refs.upload.clearFiles()
      })
    },
    uploadSuccess(data) {
      this.loadingUpload = false
      if (data.code === '200') {
        this.$message({
          message: '批量导入成功',
          type: 'success',
          duration: 2000
        })
        this.curOrgData.id = -1
        this.getOrgTreeData()
        this.uploadVisible = false
      } else {
        this.$message.error(data.msg || '批量导入失败')
        this.$refs.upload.clearFiles()
        this.curOrgData.id = -1
        this.getOrgTreeData()
        if (data.data && data.data.fileid) {
          setTimeout(() => {
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = '/API-ENTERPRISE-BACKEND/backend/sysUserLogin/downloadCheckFile' + exportSign({ errorId: data.data.fileid }).paramStr
            link.setAttribute('download', '错误信息.xls')
            link.setAttribute('target', '_blank')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }, 1000)
        }
      }
    },
    uploadError(err) {
      this.loadingUpload = false
      this.$message.error(err || '网络异常')
      this.$refs.upload.clearFiles()
    },
    uploadSubmit() {
      this.$set(this, 'uploadHeaders', importSign(this.uploadHeaders, this.uploadData))
      this.$refs.upload.submit()
      this.loadingUpload = true
    },
    handleDownload() {
      if (document.getElementById('downloadLinkFile')) {
        const dom = document.getElementById('downloadLinkFile')
        document.body.removeChild(dom)
      }
      const link = document.createElement('a')
      link.setAttribute('id', 'downloadLinkFile')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/departmentInfo/downloadTemplate' + exportSign().paramStr
      link.setAttribute('download', '部门批量导入模板.xls')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    handleCreateFirst() {
      if (this.curComData.id) {
        this.formStatus = 'create'
        this.isShow = true
        this.resetTemp()
        this.$nextTick(() => {
          this.temp.parentId = -1
          this.$refs['dataForm'].clearValidate()
        })
      } else {
        this.$message({
          type: 'info',
          message: '请选择添加一级部门的所属组织！'
        })
      }
    },
    handleCreate() {
      if (this.curComData.id) {
        this.formStatus = 'create'
        this.isShow = true
        this.$nextTick(() => {
          this.resetTemp()
          this.$refs['dataForm'].clearValidate()
        })
      } else {
        this.$message({
          type: 'info',
          message: '请选择添加一级部门的所属组织！'
        })
      }
    },
    handleUpdate() {
      this.temp = {
        orgId: this.curOrgData.orgId || '',
        parentId: this.curOrgData.parentId || '',
        code: this.curOrgData.code || '',
        name: this.curOrgData.name || '',
        status: this.curOrgData.status || '',
        sort: JSON.stringify(this.curOrgData.sort) || '',
        id: this.curOrgData.id || ''
      }
      this.formStatus = 'update'
      this.isShow = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete() {
      this.issearchtree = false
      this.delete(this.curOrgData.id)
    },
    insetOrUpdate() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          return new Promise((resolve, reject) => {
            if (this.formStatus === 'create') {
              insert(this.temp).then((res) => {
                this.isShow = false
                loading.close()
                this.$message({
                  message: this.formStatus === 'create' ? '添加成功！'
                    : '更新成功！',
                  type: 'success'
                })
                if (this.temp.parentId === '-1') { // 新增一级部门刷新当前部门树
                  this.curOrgData.id = -1
                  this.handleFilterOrgTree()
                } else {
                  this.refreshNodeBy(res.data.data.parentId)
                }
              }).catch(error => {
                reject(error)
                loading.close()
              })
            } else {
              update(this.temp).then((res) => {
                this.isShow = false
                loading.close()
                this.$message({
                  message: this.formStatus === 'create' ? '创建成功！'
                    : '编辑成功！',
                  type: 'success'
                })
                if (this.temp.parentId === '-1') { // 新增一级部门刷新当前部门树
                  this.curOrgData.id = -1
                  this.handleFilterOrgTree()
                } else {
                  this.refreshNodeBy(this.temp.parentId)
                }
              }).catch(error => {
                reject(error)
                loading.close()
              })
            }
          })
        }
      })
    },
    delete(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(ids).then((res) => {
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
          if (this.curOrgData.parentId === '-1') {
            this.curOrgData.id = -1
            this.getOrgTreeData()
          } else {
            this.refreshNodeBy(this.curOrgData.parentId)
          }
        })
      }).catch(() => {
      })
    },
    updateTreeChildren(data) {
      const node = this.$refs.bmtree.getNode(this.temp.parentId)
      if (!node) return
      const childNodes = node.childNodes
      for (let i = childNodes.length - 1; i >= 0; i--) {
        const child = childNodes[i]
        this.$refs.bmtree.remove(child.data)
      }
      for (let i = 0, j = data.length; i < j; i++) {
        const child = data[i]
        this.$refs.bmtree.append(child, node.data)
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">

$dark_gray: #bfced6;
#department-manage {
  position: relative;
  height: calc(100vh - 60px);
  padding: 10px;
  overflow: hidden;

  .enterpriseinfo {
    padding: 0px;
  }

  .org-row-container {
    height: calc(100vh - 127px);
    padding: 0px;
    overflow: hidden;

    .vue-splitter-container {
      width: 100%;
    }

    .treeBox {
      padding: 10px;
      margin-right: 0;
      background: #ffffff;
      height: 100%;
      overflow-y: auto;

      .search-tree-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .tree-filter {
          padding: 10px 18px;
        }
      }

      .el-tree-node__content {
        margin-top: 10px;
      }

      .tag {
        font-size: 12px;
        border-radius: 4px;
        padding: 2px 4px;
        color: #fff;

        &.gh {
          color: #ff7474;
          border: 1px solid #ff7474;
        }

        &.qy {
          color: #2fbcfb;
          border: 1px solid #2fbcfb;
        }

        &.bm {
          color: #ffa11c;
          border: 1px solid #ffa11c;
        }
      }

      .el-tree-node__expand-icon.expanded {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }

      .el-icon-caret-right:before {
        content: '\E7A0';
        font-size: 14px;
      }

      .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
        content: '\E7A2';
        font-size: 14px;
      }
    }

    .user-main {
      width: 100%;
      height: 100%;
      padding: 0 10px;
      position: relative;
      overflow-x: hidden;
      overflow-y: auto;
      background: #fff;

      .ts-con {
        position: absolute;
        top: 10px;
        left: 10px;
        right: 10px;
        bottom: 10px;
        background: white;

        .ts {
          line-height: 30px;
          position: absolute;
          left: 50%;
          top: 50%;
          margin-top: -15px;
          margin-left: -110px;
          width: 220px;
          text-align: center;
          background: white;
          border-radius: 2px;
          box-shadow: 1px 1px 5px #e0dbdb;
          font-size: 14px;
          font-family: Microsoft Yahei In-Bold, Microsoft Yahei,
          Apple LiGothic Medium;
          color: #222222;
        }
      }

      &::-webkit-scrollbar {
        display: none;
      }
    }
  }

  .sysconfig-search {
    background-color: #fff;
    padding: 5px 10px;
    margin-bottom: 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;

      &_login {
        font-size: 20px;
      }
    }

    .search-input {
      width: 78%;

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .el-button.is-round {
      float: right;
      padding: 10px 30px;
    }
  }

  .btn-container {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      color: rgba(51, 51, 51, 1);

      .btn-container-title-select {
        @include font-color($mainColor);
      }
    }
  }

  .el-dialog--center .el-dialog__body {
    text-align: center;
  }
}
</style>
